#step1 数据预处理
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
data = load_iris()
train_data, test_data, train_target, test_target = \
train_test_split(data.data, data.target, test_size=0.2, random_state=1)
iris = load_iris()
#step2 建模
from sklearn import tree
clf=tree.DecisionTreeClassifier(criterion='entropy') #使用分类器，采用熵增益
clf.fit(train_data,train_target)
#step3 预测
y_pred=clf.predict(test_data)
#step4 验证
from sklearn import metrics
print(metrics.accuracy_score(y_true=test_target,y_pred=y_pred))
print(metrics.confusion_matrix(y_true=test_target,y_pred=y_pred))
#以图形方式输出结果
import matplotlib.pyplot as plt
plt.figure(dpi=300)
tree.plot_tree(clf,filled=True)
plt.show()
#以文本方式输出结果
r = tree.export_text(clf, feature_names=iris['feature_names'])
print(r)
#以文件方式输出结果
with open('tree.dot','w') as fw:
    tree.export_graphviz(clf,out_file=fw)